﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace SNSpirit.IO
{
    internal class FileRepository
    {
        public FileRepository(RepositoryIdentity id)
        {
            if (id == null)
                throw new ArgumentNullException("id");
            this._allFiles = new List<string>();
            this.AllFiles = new ReadOnlyCollection<string>(this._allFiles);
        }

        public ReadOnlyCollection<string> AllFiles { get; private set; }

        public virtual string GetNewRandomFileName()
        {
            lock (this._syncRoot)
            {
                string filename = Path.GetTempFileName();
                this._allFiles.Add(filename);
                return filename;
            }
        }
        /// <summary>
        /// Get full file name
        /// </summary>
        /// <param name="filename">short filename</param>
        /// <returns></returns>
        public virtual string GetNewFilename(string filename)
        {
            lock (this._syncRoot)
            {
                string fullFilename = Path.Combine(Path.GetTempPath(), filename);
                this._allFiles.Add(filename);
                return fullFilename;
            }
        }

        public virtual void AttachFile(string filename)
        {
            if (filename == null)
                throw new ArgumentNullException("filename");
            lock (this._syncRoot)
            {
                if(!this._allFiles.Contains(filename))
                    this._allFiles.Add(filename);
            }
        }

        public virtual void DetachFile(string filename)
        {
            if (filename == null)
                throw new ArgumentNullException("filename");
            lock (this._syncRoot)
            {
                if (this._allFiles.Contains(filename))
                    this._allFiles.Remove(filename);
            }
        }

        public virtual void Clean()
        {
            try
            {
                foreach (var file in this.AllFiles)
                    if(File.Exists(file))
                        File.Delete(file);
            }
            catch (Exception error)
            {

            }
        }

        #region private

        private RepositoryIdentity _id;

        private readonly object _syncRoot = new object();

        private List<string> _allFiles;

        #endregion
    }
}
